<template>
  <!-- 搜索栏事件监听 -->
  <!-- search事件表示用户点击搜索按钮时触发onSearch事件 -->
  <!-- cancel事件	点击取消按钮时触发 -->
  <div class="search-container">
    <form action="/" class="form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="#3296FA"
        @focus="isResultShow = false"
        :autofocus="true"
      />
    </form>

    <!-- 搜索结果 -->
    <!-- 默认搜索结果组件是隐藏的，只有当用户在输入框输入内容并且点击search按钮或者电脑键盘上的enter键时，才会触发search事件让搜索结果组件显示 -->
    <SearchResult v-if="isResultShow" :searchText="searchText"></SearchResult>
    <!-- 联想建议 -->
    <!-- 联想建议组件是在用户输如内容时就进行显示； -->
    <SearchSuggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></SearchSuggestion>

    <!-- 历史记录默认进行显示 -->
    <!-- 搜索历史记录 -->
    <SearchHistory
      v-else
      :searchHistory="searchHistories"
      @clear-search-history="searchHistories = []"
      @search="onSearch"
    ></SearchHistory>
  </div>
</template>

<script>
// 引入搜素历史、联想建议、搜索结果组件
import SearchHistory from "./components/search-history";
import SearchSuggestion from "./components/search-suggestion";
import SearchResult from "./components/search-result";
import { setItem, getItem } from "@/utils/storage.js";
export default {
  name: "searchIndex",
  data() {
    return {
      searchText: "",
      isResultShow: false,
      searchHistories: getItem("serach-histories") || [],
    };
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult,
  },
  created() {},

  methods: {
    onSearch(val) {
      //   this.$toast(val);
      this.searchText = val;
      // 存储搜索历史记录
      // 要求：不要有重复历史记录、最新的排在最前面
      const index = this.searchHistories.indexOf(val);
      if (index !== -1) {
        this.searchHistories.splice(index, 1);
      }
      this.searchHistories.unshift(val);

      this.isResultShow = true;
    },
    onCancel() {
      //   this.$toast("取消");
      this.$router.back();
    },
  },

  watch: {
    searchHistories(val) {
      console.log("侦听的变化是", val);
      // 同步到本地存储
      setItem("serach-histories", val);
    },
  },
};
</script>

<style scoped lang='less'>
.search-container {
  .form {
    position: fixed;
    z-index: 11;
    width: 100%;
  }
  .van-search {
    .van-search__content {
      border-radius: 25px;
      background-color: #f5f5f6;
    }
  }
  .search-history {
    padding-top: 100px;
  }
}
</style>